package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.queryForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(StrategyDetail entity) {

        //判断序号是否为null
        if(entity.getSequence()==null){
            //获取当前的攻略分类中攻略文章最大的序号
            Integer max = strategyDetailMapper.selectMaxSequence(entity.getCatalog().getId());
            if (max!=null){
                entity.setSequence(max+1);
            }else{
                entity.setSequence(0);
            }
        }

        //获取攻略内容对象
        StrategyContent strategyContent = entity.getStrategyContent();
        if(entity.getId()!=null){
            //更新攻略文章
            strategyDetailMapper.updateByPrimaryKey(entity);
            //更新攻略内容表
            strategyContent.setId(entity.getId());
            contentMapper.updateByPrimaryKey(strategyContent);
        }else{
            Date date = new Date();
            entity.setCreateTime(date);
            //判断是否是发布状态
            if(entity.getState()==StrategyDetail.STATE_RELEASE){
                entity.setReleaseTime(date);
            }
            //保存攻略文章
            strategyDetailMapper.insert(entity);
            //新增攻略内容表
            strategyContent.setId(entity.getId());
            contentMapper.insert(strategyContent);
        }
    }

    public StrategyContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public StrategyDetail getDetailById(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }
}
